﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using SmartAnswerPlatform.IRepository;
using SmartAnswerPlatform.IService;
using SmartAnswerPlatform.Repository;
using SmartAnswerPlatform.Service;
using System.Reflection;

namespace SmartAnswerPlatform.WebApi
{
    public class AutofacModuleRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            Assembly repositoryAssembly = typeof(BaseRepository<>).Assembly;
            Assembly serviceAssembly = typeof(BaseService<,>).Assembly;

            if (repositoryAssembly == null)
            {
                throw new Exception("仓储层程序集为空！");
            }

            if (serviceAssembly == null)
            {
                throw new Exception("业务层程序集为空！");
            }

            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();//注册仓储
            builder.RegisterGeneric(typeof(BaseService<,>)).As(typeof(IBaseService<,>)).InstancePerDependency();//注册仓储

            builder.RegisterAssemblyTypes(repositoryAssembly)
                //使用接口的方式进行注入
                .AsImplementedInterfaces()
                //单例注入
                .SingleInstance()
                //适用于接口和实现类
                .EnableInterfaceInterceptors()
                ;


            builder.RegisterAssemblyTypes(serviceAssembly)
                //使用接口的方式进行注入
                .AsImplementedInterfaces()
                //单例注入
                .SingleInstance()
                //适用于接口和实现类
                .EnableInterfaceInterceptors()
                ;


        }
    }
}
